package com.xinongbest.mall.util;

import com.xinongbest.mall.common.Constant;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lemonwan
 * MD5加密工具
 */
public class MD5Utils {
    /**
     * 通过对字符加上一个约定的字符进行加密
     *
     * @param string
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getMD5Str(String string) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        return Base64.encodeBase64String(digest.digest((string + Constant.SALT).getBytes()));
    }

    /**
     * 通过字符偏移量运算对字符进行加密
     *
     * @param sourceString
     * @return
     */
    public static String md5Digest(String sourceString) {
        char[] charArray = sourceString.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = (char) (charArray[i] + Constant.SALT_NUM);
        }
        String digestStr = new String(charArray);
        return DigestUtils.md5DigestAsHex(digestStr.getBytes());
    }
}
